<?php
namespace app\common\model\newmodel;

use think\Model;
use app\common\model\newmodel\UserFactory;
use app\common\model\newmodel\User;
use app\common\model\newmodel\UserAgency;
use app\common\model\newmodel\Accessories;
use app\common\model\newmodel\Device;
use app\common\model\newmodel\Customer;
use think\Db;

class ContractOrder extends Model
{
    protected $table = 'contract_order';
    protected $pk = 'id';

    public function devices()
    {
        return $this->belongsTo('app\\common\\model\\newmodel\\Device', 'device_id', 'id')->field('id,device_name');
    }

    public function contract()
    {
        return $this->belongsTo('app\\common\\model\\newmodel\\Contract', 'contract_id', 'id')->field('id,contract_name,img_url,recipient_name,recipient_tel,recipient_address');
;
    }

    public function customer()
    {
        return $this->belongsTo('app\\common\\model\\newmodel\\Customer', 'customer_id', 'CustomerId')->field('CustomerId,Name,Address,UserName,Tel');
    }

    public function factory()
    {
        return $this->belongsTo('app\\common\\model\\newmodel\\Factory', 'factory_id', 'id');
    }
 
    /**
     * 拆单（生成订单
     */
    public static function createProductOrders($data)
    {
        // 检查该合同是否已生成订单
        $orderData = self::where('State', 1)->where('contract_id', $data['contract_id'])->select()->toArray();
        if ($orderData) {
            return ['code' => 0, 'msg' => '该合同已经生成订单，如果要重新生成，请先删除原来的订单'];
        }
        
        if (empty($data['contract_id']) || empty($data['order_items']) || empty($data['customer_id'])) {
            return ['code' => 0, 'msg' => '参数不完整'];
        }
        
        $currentTime = time();
        $orderIds = [];
        
        self::startTrans();
        try {
            // 处理每个设备及其配件
            foreach ($data['order_items'] as $item) {
                $deviceId = $item['device_id'];
                $deviceQuantity = $item['quantity'] ?? 1;
                
                // 获取设备信息
                $device = Device::where('id', $deviceId)->find();
                if (!$device) {
                    continue;
                }
                
                $factoryId = $device['factory_id'];
                
                // 处理配件信息
                $accessorySkus = [];
                $accessoryIds = [];
                
                if (!empty($item['accessories'])) {
                    foreach ($item['accessories'] as $accessory) {
                        $accessoryIds[] = $accessory['id'];
                        $accessorySkus[] = [
                            'accessory_id' => $accessory['id'],
                            'accessory_name' => $accessory['accessory_name'],
                            'sku_id' => $accessory['sku_id'],
                            'sku_value' => $accessory['sku_value']
                        ];
                    }
                }
                
                // 创建订单
                $order = new self();
                $order->contract_id = $data['contract_id'];
                $order->device_id = $deviceId;
                $order->accessories_id = implode(',', $accessoryIds);
                $order->factory_id = $factoryId;
                $order->customer_id = $data['customer_id'];
                $order->device_quantity = $deviceQuantity;
                $order->accessory_skus = json_encode($accessorySkus, JSON_UNESCAPED_UNICODE);
                $order->track_number = $data['track_number'] ?? '';
                $order->status = 1;
                $order->create_time = $currentTime;
                $order->update_time = $currentTime;
                $order->recipient_address=$item['shipping_info']['recipient_address'] ?? null;
                $order->recipient_name=$item['shipping_info']['recipient_name'] ?? null;
                $order->recipient_tel=$item['shipping_info']['recipient_tel'] ?? null;
                $order->remark=$item['shipping_info']['remark'] ?? null;
                $order->save();
                $orderIds[] = $order->id;
            }
            
            self::commit();
            
            return [
                'code' => 1,
                'msg' => '生成订单成功',
                'order_ids' => $orderIds,
                'order_count' => count($orderIds)
            ];
        } catch (\Exception $e) {
            self::rollback();
            return ['code' => 0, 'msg' => '生成订单失败：' . $e->getMessage()];
        }
    }

    /**
     * 订单列表（多角色，工厂订单按工厂ID区分）
     */
    public static function getOrderList($userId, $page = 1, $pageSize = 10, $keyword = '', $status='')
    {
        $user = User::get($userId);
        if (!$user) {
            return ['code' => 0, 'msg' => '用户不存在'];
        }
        $role = $user->Role;
        $query = self::with(['devices','contract', 'customer', 'factory']);

        // 工厂管理员/员工
        if (in_array($role, [301, 302])) {
    
            $factoryId = UserFactory::getFactoryIdByUserId($userId);
            if (!$factoryId) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $query = $query->where('factory_id', $factoryId);
        }
        // 代理商管理员
        elseif ($role == 401) {
            $agencyId = UserAgency::getAgencyIdByUserId($userId);
            if (!$agencyId) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $agencyUserIds = UserAgency::getUserIdsByAgencyId($agencyId);
            $customerIds = Customer::where('LatestAgentId', 'in', $agencyUserIds)->column('CustomerId');
            if (empty($customerIds)) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $query = $query->where('customer_id', 'in', $customerIds);
        }
        // 代理商员工
        elseif ($role == 402) {
            $customerIds = Customer::where('LatestAgentId', $userId)->column('CustomerId');
            if (empty($customerIds)) {
                return ['code' => 1, 'msg' => 'success', 'data' =>''];
            }
            $query = $query->where('customer_id', 'in', $customerIds);
        }
        // 业务员
        elseif ($role == 201) {
            // 业务员只能看非代理商客户的订单
            $customerIds = Customer::where('LatestAgentId',0)->column('CustomerId');
            if (empty($customerIds)) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $query = $query->where('customer_id', 'in', $customerIds);
        }
        // 其它角色无权限
        else {
            return ['code' => 0, 'msg' => '无权限'];
        }

        if (!empty($keyword)) {
            $query = $query->where('track_number', 'like', "%{$keyword}%");
        }
        if (!empty($status)) {
            $query = $query->where('status',$status);
        }

        $list = $query->order('create_time desc')
                ->where('State',1)
                ->paginate([
                    'list_rows' => $pageSize,
                    'page' => $page,
                ]);

        $items = $list->toArray();

        // 处理配件规格信息
        if (!empty($items['data'])) {
            foreach ($items['data'] as &$item) {
                $accessoryIds = array_filter(explode(',', $item['accessories_id'] ?? ''));
                $accessories = [];
                if ($accessoryIds) {
                    $accessories = Accessories::where('id', 'in', $accessoryIds)
                        ->field('id, accessory_name')
                        ->select()
                        ->toArray();
                }
                $item['accessories'] = $accessories;
                
                //解析accessory_skus为数组
                if (!empty($item['accessory_skus'])) {
                    $decodedSkus = json_decode($item['accessory_skus'], true, 512, JSON_THROW_ON_ERROR);
                    $item['accessory_skus'] = is_array($decodedSkus) ? $decodedSkus : [];
                } else {
                    $item['accessory_skus'] = [];
                }
                unset($item['device_id']);
                unset($item['accessories_id']);
                unset($item['factory_id']);
                unset($item['contract_id']);
                unset($item['customer_id']);
            }
            unset($item); 
        }
        
        return [
            'code' => 1,
            'msg' => 'success',
            'data' => $items 
        ];
    }

    /**
     * 订单状态修改
     */
    public static function updateOrderStatus($data)
    {
        if (empty($data['id'])) {
            return json(['code' => 0, 'msg' => '参数不完整']);
        }
        $orderId=$data['id'];
        $order = self::get($orderId);
        if (!$order) {
            return ['code' => 0, 'msg' => '订单不存在'];
        }
        
        $order->track_number =$data['track_number'] ?? '';
        $order->status = $data['status'] ?? '';
        $order->update_time = time();
        $order->remark=$data['remark'] ?? '';
        $order->save();
        return ['code' => 1, 'msg' => '修改成功'];
    }

    /**
     * 根据合同ID获取订单详情
     */
    public static function getOrdersByContractId($contract_id)
    {
        if(empty($contract_id)){
            return ['code' =>0,'msg' => '参数不完整'];
        }
        $query= self::with(['devices','factory'])->where('State',1)->where('contract_id',$contract_id)->select()->toArray();
        if ($query) {
            foreach ($query as &$item) {
                $accessoryIds = array_filter(explode(',', $item['accessories_id'] ?? ''));
                $accessories = [];
                if ($accessoryIds) {
                    $accessories = Accessories::where('id', 'in', $accessoryIds)
                        ->field('id, accessory_name')
                        ->select()
                        ->toArray();
                }
                $item['accessories'] = $accessories;
                 if (!empty($item['accessory_skus'])) {
                    $decodedSkus = json_decode($item['accessory_skus'], true, 512, JSON_THROW_ON_ERROR);
                    $item['accessory_skus'] = is_array($decodedSkus) ? $decodedSkus : [];
                } else {
                    $item['accessory_skus'] = [];
                }
                unset($item['device_id']);
                unset($item['accessories_id']);
                unset($item['factory_id']);
                unset($item['contract_id']);
                unset($item['customer_id']);
            }
            unset($item); 
        }else{
            return ['code'=>0,'msg'=>'暂无订单信息'];
        }
        return [
            'code' => 1,
            'msg' => 'success',
            'data' => $query 
        ];
        
    }

    //工厂确认该订单，有待处理状态改为生产中
    public static function confirmOrder($id)
    {
        if(empty($id)){
            return ['code'=>false,'msg'=>'参数不完整'];
        }
        $order=self::get($id);
        if(!$order){
            return ['code'=>'false','msg'=>'该订单不存在'];
        }
        $order->status = 2;
        $order->update_time=time();
        $order->save();
        return ['code'=>true,'msg'=>'订单确认成功'];
    }

    //去发货
    public static function goShipGoods($data)
    {
        $id=$data['id'];
        $order = self::get($id);
        if(!$order){
            return ['code'=>false,'msg'=>'该订单不存在'];
        }
        $order->track_number=$data['track_number'];
        $order->logistics_document_img=$data['logistics_document_img'];
        $order->device_img=$data['device_img'];
        $order->status =3;
        $order->update_time=time();
        $order->save();
        return ['code'=>true,'msg'=>'发货成功'];
    }

    //转单处理
    public static function transferOrder($order_id,$factory_id,$transfer_remark='')
    {
        if(empty($order_id) || empty($factory_id)){
            return ['code'=>false,'msg'=>'参数不完整'];
        }
        $order=self::get($order_id);
        if(!$order){
            return ['code'=>'false','msg'=>'该订单不存在'];
        }
        $order->factory_id=$factory_id;
        $order->transfer_remark=$transfer_remark;
        //订单状态改为待处理，
        $order->status=1;
        $order->update_time=time();
        $order->save();
        return ['code'=>true,'msg'=>'订单转单成功'];
    }
    
    /*
    public static function getOrderList($userId, $page = 1, $pageSize = 10, $keyword = '')
    {
        $user = User::get($userId);
        if (!$user) {
            return ['code' => 0, 'msg' => '用户不存在'];
        }
        $role = $user->Role;
        $query = self::with(['devices','contract', 'customer', 'factory']);

        // 工厂管理员/员工
        if (in_array($role, [301, 302])) {
            // 工厂ID
            $factoryId = UserFactory::getFactoryIdByUserId($userId);
            if (!$factoryId) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $query = $query->where('factory_id', $factoryId);
        }
        // 代理商管理员
        elseif ($role == 303) {
            $agencyId = UserAgency::getAgencyIdByUserId($userId);
            if (!$agencyId) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $agencyUserIds = UserAgency::getUserIdsByAgencyId($agencyId);
            $customerIds = Customer::where('AgentId', 'in', $agencyUserIds)->column('CustomerId');
            if (empty($customerIds)) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $query = $query->where('customer_id', 'in', $customerIds);
        }
        // 代理商员工
        elseif ($role == 304) {
            $customerIds = Customer::where('AgentId', $userId)->column('CustomerId');
            if (empty($customerIds)) {
                return ['code' => 1, 'msg' => 'success', 'data' =>''];
            }
            $query = $query->where('customer_id', 'in', $customerIds);
        }
        // 业务员
        elseif ($role == 201) {
            // 业务员只能看非代理商客户的订单
            $customerIds = Customer::where('IsAgent', 0)->column('CustomerId');
            if (empty($customerIds)) {
                return ['code' => 1, 'msg' => 'success', 'data' => ''];
            }
            $query = $query->where('customer_id', 'in', $customerIds);
        }
        // 其它角色无权限
        else {
            return ['code' => 0, 'msg' => '无权限'];
        }

        // 物流单号关键词搜索
        if (!empty($keyword)) {
            $query = $query->where('track_number', 'like', "%{$keyword}%");
        }

        $list = $query->order('create_time desc')
        ->paginate([
            'list_rows' => $pageSize,
            'page' => $page,
        ]);

        return [
            'code' => 1,
            'msg' => 'success',
            'data' => $list
        ];
    }
     */

   
}